package mcommand;

import java.util.Observable;
import java.util.Observer;

/**
 * Handles the statistic, also how to load and write
 * into a xml file.
 *
 * @author Marcel, Christian, Klaus
 *
 */
public class Statistics implements Observer {
    // sets the statistic value on a standard 0 value
    private static int rocketCounter = 0;
    private static int rocketHitCounter = 0;

    // defines a new xml reader
    private static ToolXMLReader xmlreader;

    // a board variable for debug mode check
    private Board parent;

    /**
     * If there is no filled xml reader, a new is created
     * and the variables are filled with the values
     * of the xml file.
     *
     * @param parent parent
     */
    public Statistics(final Board parent) {
        this.parent = parent;
        
        readStatisticsFromXML();
    }

    /**
     * Updates the rocketCounter and rocketHitCounter values.
     * 
     * @param arg0 source of observable
     * @param arg1 type of event
     */
    public final void update(final Observable arg0, final Object arg1) {
        if (arg1.equals(StatisticType.ROCKET_FIRED)) {
            rocketCounter++;

            //if we are in DEBUG mode print a message out
            if (parent.DEBUG) {
                System.out.println("Stats - RocketCounter++");
            }
        } else if (arg1.equals(StatisticType.ROCKET_HIT)) {
            rocketHitCounter++;

            //if we are in DEBUG mode print a message out
            if (parent.DEBUG) {
                System.out.println("Stats - RocketHitCounter++");
            }
        }
    }

    /**
     * Writes the statistic data into xml.
     */
    public static void writeStatisticsIntoXML() {
        ToolXMLWriter.writeStatisticsIntoXML(rocketCounter, rocketHitCounter);
    }

    /**
     * Reads the statistic data from xml.
     */
    public static void readStatisticsFromXML() {
        if (xmlreader == null) {
            xmlreader = new ToolXMLReader();
        }

        rocketCounter = xmlreader.readStatistics("rocketCount");
        rocketHitCounter = xmlreader.readStatistics("rocketHitCount");
    }

    /**
     * Resets the statistic values.
     */
    public static void resetStatistics() {
        rocketCounter = 0;
        rocketHitCounter = 0;

        writeStatisticsIntoXML();
    }

    /**
     * Returns the rocketCounter value.
     * @return rocketCounter rocketCounter
     */
    public static int getRocketCounter() {
        return rocketCounter;
    }

    /**
     * Returns the rocketHitCounter value.
     * @return rocketHitCounter rocketHitCounter
     */
    public static int getRocketHitCounter() {
        return rocketHitCounter;
    }

    /**
     * Holds the statistic types.
     *
     */
    public enum StatisticType {
        ROCKET_FIRED,
        ROCKET_HIT
    }
}
